﻿using System.Text.Json.Serialization;
using Core.Caching;
using Core.Identity.Common.Interfaces.Common.Interfaces;
using Core.Identity.Roles.Caching;
using Core.Identity.Roles.Dtos;
using Core.Models;
using Mapster;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Core.Identity.Roles.Features.Queries.GetMenusById;


/// <summary>
/// 根据Id获取角色菜单
/// </summary>
public class GetRoleMenusByIdQuery : ICacheableRequest<Result<IEnumerable<RoleMenuDto>>>
{
    /// <summary>
    /// 角色Id
    /// </summary>
    public Guid RoleId { get; set; }

    /// <summary>
    /// 缓存键
    /// </summary>
    [JsonIgnore]
    public string CacheKey => RolesCacheKey.GetRoleMenusByIdCacheKey(RoleId.ToString());

    /// <summary>
    /// 缓存选项
    /// </summary>
    [JsonIgnore]
    public IEnumerable<string>? Tags => RolesCacheKey.Tags;
}

public class GetRoleMenusByIdQueryHandler :
         IRequestHandler<GetRoleMenusByIdQuery, Result<IEnumerable<RoleMenuDto>>>
{
    private readonly IIdentityDbContext _context;

    public GetRoleMenusByIdQueryHandler(
        IIdentityDbContext context)
    {
        _context = context;
    }

    public async Task<Result<IEnumerable<RoleMenuDto>>> Handle(GetRoleMenusByIdQuery request, CancellationToken cancellationToken)
    {
        var roleMenus = await _context.RolePermissions
            .AsNoTracking()
               .Include(rp => rp.Permission)
            .Where(rp => rp.RoleId == request.RoleId)
            .Select(rp => rp.Permission)
            .Distinct()
            .OrderByDescending(p => p.Sort)
            .ToListAsync(cancellationToken);

        return await Result<IEnumerable<RoleMenuDto>>
            .SucceedAsync(roleMenus.Adapt<IEnumerable<RoleMenuDto>>());
    }
}
